package beanpay

import (
	"gitee.com/micro-plat/fas/modules/const/enum"
	"gitee.com/micro-plat/fas/modules/sdkdb"
	"github.com/asaskevich/govalidator"
	"github.com/micro-plat/beanpay/beanpay"
	"github.com/micro-plat/lib4go/errs"
)

//DownChannelPay 下游扣款
func DownChannelPay(params *DownPay) (err error) {

	// 验证参数
	if b, err := govalidator.ValidateStruct(params); !b {
		return errs.NewErrorf(406, "BPay:DownChannelPay:govalidator.参数验证错误err:%+v,param:%+v", err, params)
	}

	// 获取beanpay接口
	// 获取数据操作对象
	_, trans, err := sdkdb.GetDBTrans(nil)
	if err != nil {
		return err
	}
	bp := beanpay.GetAccount(params.Ident, enum.AccountGroups.DownChannel)
	if params.DownSellAmount > 0 {
		_, err = bp.DeductAmount(trans, params.DownChannelNo, params.TradeOrderNo, beanpay.TPTrade, params.DownSellAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "渠道账户扣款失败,err:%v", err)
		}
	}

	// 手续费扣款
	if params.DownFeeAmount > 0 {
		_, err = bp.DeductAmount(trans, params.DownChannelNo, params.TradeOrderNo, beanpay.TPFree, -params.DownFeeAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "渠道账户手续费扣款失败，err:%v", err)
		}
	}
	// 佣金加款
	if params.DownCommissionAmount != 0 {
		_, err := beanpay.GetAccount(params.Ident, enum.AccountGroups.DownCommission).AddAmount(
			trans, params.DownChannelNo, params.TradeOrderNo, params.DownCommissionAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "佣金账户加款失败，err:%v", err)
		}
	}

	// 服务费加款
	if params.DownServiceAmount != 0 {
		_, err := beanpay.GetAccount(params.Ident, enum.AccountGroups.DownService).AddAmount(
			trans, params.DownChannelNo, params.TradeOrderNo, params.DownServiceAmount, params.Memo)
		if err != nil {
			trans.Rollback()
			return errs.NewErrorf(errs.GetCode(err), "服务费账户加款失败，err:%v", err)
		}
	}

	trans.Commit()
	return
}
